<?php
/**
 * Created by PhpStorm.
 * User: fenfen
 * Date: 2016/11/17
 * Time: 10:45
 */

namespace frontend\controllers;

use bc\controller\FrontController;
use bc\controller\WxOAuthController;
use bc\model\order\DetailModel;
use bc\model\OrderModel;
use bc\model\ProductModel;
use bc\model\shop\WxUserModel;
use bc\model\wc\BookingModel;
use bc\model\wc\BpointModel;
use bc\model\wc\DoctorModel;
use bc\model\wc\ConfirmModel;
use bc\model\wc\SpreadModel;
use bc\model\wc\StaffModel;
use bc\model\wx\report\CodeModel;
use yii\web\Session;
use bc\wx\OAuth;
use bc\wx\Auth;
use bc\model\wx\User as wxUser;
use bc\model\ecs\UserModel as ecsUser;
use bc\wx\User as User;
use bc\model\UserModel as zUser;
use bc\util\Util;
use bc\model\wc\AgentModel;
class BookingController extends WxOAuthController
{
    protected $userInfop=0;
    protected  $attention=0;
    protected $openid=null;

    /*
     * 初始化
     * */
    public function init()
    {

        parent::init(); // TODO: Change the autogenerated stub
        $session = new Session ();
        $user = $session->get('user');
        $this->openid = $user ['openid'];

        //判断是否关注
        $this->userInfop = $this->getUserInfo($this->openid);
        if ($this->userInfop['subscribe']) {
            $this->attention = 1;
        }

    }

    /*
     * 获取用户基本信息
     * */
    public function getUserInfo($openid)
    {
        $appid = $this->wechat()->appid;
        $secret = $this->wechat()->secret;

        $auth = new Auth($appid, $secret);
        $accessToken = $auth->accessToken;

        $user = new User();

        $info = $user->getUserInfo($accessToken, $openid);
        return $info;
    }

    /*
     * 首页
     * */
    public function actionIndex()
    {
        $zUserid=0;
        $userModel = new zUser();
        $whereUserModel =  array('wxid'=>$this->openid);
        $userModelRow = $userModel->getRow($whereUserModel);
        if(empty($userModelRow)){
            if(empty($this->openid))
                $this->redirect('/booking/index');
            $zUserid=$userModel->saveDate($this->openid);
        }else{
            $zUserid=$userModelRow['id'];
        }

//        $bookingModel = new BookingModel();
//        $whereUserModel =  array('user_id'=>$zUserid);
//        $bookingModelRow = $bookingModel->getRow($whereUserModel);
//        $row['id'] = $bookingModelRow['id'];

        
        //个人无创推广 生成绑定关系
        $agent_id = $this->get('agent_id');
        if($agent_id)
        {
        	$agentModel = new AgentModel();
        	$agent = $agentModel->getRowById($agent_id);
        	if($agent)
        	{
        		//设置COOKIE 有效期一天
        		$rspCookies = $this->response()->cookies;
        		$rspCookies->add(new \yii\web\Cookie([
        				'name' => 'recommend_wc',
        				'value' => $agent['user_id'],
        				'expire'=>time()+3600*24,
        		]));
        	}
        
        }
        
        $bookingModel = new BookingModel();
        $userInfo=$bookingModel->getUserInfo($this->openid );

        $row['userInfo'] = $userInfo;
        return $this->render ( 'index',$row );
    }

    /*
     * 协议书
     * */
    public function actionRule()
    {
        return $this->render ( 'rule' );
    }

    public function actionForm()
    {
        $session = new Session ();
        $user = $session->get ( 'user' );

        $id = $this->get ( 'id' );

        //设定默认的订单号
        $orderNo  = date('YmdHis') . rand(10000000,99999999);
        if($id)
        {

            // 页面数据信息
            $bookingModel = new BookingModel ();
            $whereUserModel = array (
                'id' => $id
            );
            $bookingModelRow = $bookingModel->getRow ( $whereUserModel );

            $userModel = new zUser ();
            $whereUserModel = array (
                'id' => $bookingModelRow ['user_id']
            );
            $userModelRow = $userModel->getRow ( $whereUserModel );
            $bookingModelRow ['name'] = $userModelRow ['real_name'];
            $bookingModelRow ['idcard'] = $userModelRow ['idcard'];
            $bookingModelRow ['idcard_type'] = $userModelRow ['idcard_type'];
            $bookingModelRow ['birthday'] = $userModelRow ['birthday'];
            $bookingModelRow ['mobile'] = $userModelRow ['mobile'];

            $orderNo = $bookingModelRow['order_no'];
            $view ['row'] = $bookingModelRow;
            // end
        }

        //获取采血点和医生
        $bpointModel= new BpointModel();
        $bpointList=$bpointModel->getList(array('is_invalid'=>1));

//        $doctorModel= new DoctorModel();
//        $doctorModel->columns='bc_wc_doctor.id as d_id,user_id,hospital_id,phone,bc_wc_hospital.id as h_id,name,address,bc_user.id as uid,real_name,nick_name,wxid';
//        $doctorList=$doctorModel->getDoctorList(array('bc_wc_doctor.is_invalid'=>1));

        $view ['bpointList'] = $bpointList;
//        $view ['doctorList'] = $doctorList;
//        $view ['jsApiParameters'] = $jsApiParameters;
        return $this->render ( 'form', $view );
/*
        $id=$this->get('id','');
        if(!empty($id)) {
            $id=$this->get('id','');
            $bookingModel = new BookingModel();
            $whereUserModel =  array('id'=>$id);
            $bookingModelRow = $bookingModel->getRow($whereUserModel);


            //获取用户信息
            $userModel = new zUser();
            $whereUserModel =  array('id'=>$bookingModelRow['user_id']);
            $userModelRow = $userModel->getRow($whereUserModel);
            $bookingModelRow['name'] = $userModelRow['real_name'];
            $bookingModelRow['idcard'] = $userModelRow['idcard'];
            $bookingModelRow['birthday'] = $userModelRow['birthday'];
            $bookingModelRow['mobile_phone'] = $userModelRow['mobile_phone'];
            $row['bookingModelRow'] = $bookingModelRow;
            return $this->render ( 'form',$row );
        }else{
            $userDate['real_name'] = $this->get('name', '');
            $userDate['birthday'] = $this->get('duedate', '');
            $userDate['mobile_phone'] = $this->get('mobile', '');
//        $userDate['code']=$this->get('code','');
            $userDate['idcard'] = $this->get('idcard', '');
            $userDate['update_time'] = time();
            $userDate['is_invalid'] = 1;
            if (!empty($userDate['real_name']) && !empty($userDate['mobile_phone'])) {
                //更新bc_user表
                $userModel = new zUser();
                $whereUserModel = array('wxid' => $this->openid);
                $userModelRow = $userModel->getRow($whereUserModel);
                $userModel->modify($userDate, $userModelRow['id']);

                $data['childbirth_date'] = $this->get('birthday');
                $data['bpoint_id'] = $this->get('collection');
                $data['doctor_id'] = $this->get('doctor');
                $data['user_id'] = $userModelRow['id'];
//                $data['user_id'] = $user_id;
                $data['update_time'] = time();
                $data['is_invalid'] = 1;
                $data['status'] = 1;
                $data['report_url'] = "";

                $bookingModel = new BookingModel();
                $whereUserModel =  array('user_id'=>$userModelRow['id']);
                $bookingModelRow = $bookingModel->getRow($whereUserModel);
                if(empty($bookingModelRow)){
                    $session = new Session ();
                    $shop_user = $session->get('shop_user');
                    $user_id=$shop_user['user_id'];
                    $data['order_no']  = date('YmdHis') . rand(10000000,99999999);
                    //获取无创产品数据
                    $productM = new ProductModel();
                    $productD=$productM->getRowById(1);
                    //插入order表
                    $orderData['user_id'] = $user_id;
                    $orderData['order_no'] = $data['order_no'];
                    $orderData['pay_amount'] = $productD['product_price'];
                    $orderData['order_amount'] = $productD['product_price'];
                    $orderData['pay_status'] = 0;
                    $orderData['order_status'] = 1;
                    $orderData['create_time'] = time();
                    $orderData['update_time'] = time();

                    $OrderM = new OrderModel();
                    $returnid_order = $OrderM->add($orderData);
                    $OrderM->save();
                    $data['order_id'] = $returnid_order;
                    $data['create_time'] = time();

                    $returnid_booking = $bookingModel->add($data);
                }else{
                    $returnid=$bookingModelRow['id'];
                    $bookingModel->modify($data, $bookingModelRow['id']);
                }
                if ($returnid) ;
                {
                    //获取数据输出
//                return $this->render ( 'forminfo' );
                    $url = $this->getRequest()->hostInfo . '/wxpay/?id=' . $returnid_order;
                    $this->redirect($url);
                }
            }
            return $this->render ( 'form' );
        }*/
    }

    /*
	 * 页面数据保存
	 */
    public function actionSavedate()
    {
        $session = new Session ();
        $user = $session->get ( 'user' );
        $userDate ['real_name'] = $this->post ( 'name', '' );
        $userDate ['birthday'] = $this->post ( 'birthday', '' );
        $userDate ['mobile'] = $this->post ( 'mobile', '' );
        $userDate ['idcard'] = $this->post ( 'idcard', '' );
        $userDate ['idcard_type'] = $this->post ( 'idcard_type', '' );
        $userDate ['update_time'] = date ( 'Y-m-d H:i:s', time () );
        $userDate ['is_invalid'] = 1;
        // 更新bc_user表
        $userModel = new zUser ();
        $whereUserModel = array (
            'wxid' => $user ['openid']
        );
        $userModelRow = $userModel->getRow ( $whereUserModel );
        $userModel->modify ( $userDate, $userModelRow ['id'] );

        $data ['childbirth_date'] = $this->post ( 'duedate' );
        $data ['bpoint_id'] = $this->post ( 'collection' );
        // $data['doctor_id'] = $this->post('doctor');
        $data ['user_id'] = $userModelRow ['id'];
        $data ['update_time'] = time ();
        $data ['is_invalid'] = 1;
        $data ['status'] = 1;
        $data ['report_url'] = "";

        $bookingModel = new BookingModel ();
        $whereUserModel = array (
            'user_id' => $userModelRow ['id']
        );
        $bookingModelRow = $bookingModel->getRow ( $whereUserModel );
        if (empty ( $bookingModelRow ))
        {
            $session = new Session ();
            $shop_user = $session->get('shop_user');
            $user_id=$shop_user['user_id'];
            $data['order_no']  = date('YmdHis') . rand(10000000,99999999);
            //获取无创产品数据
            $productM = new ProductModel();
            $productD=$productM->getRowById(1);
            //插入order表
            $orderData['user_id'] = $user_id;
            $orderData['order_no'] = $data['order_no'];
            $orderData['pay_amount'] = $productD['product_price'];
            $orderData['order_amount'] = $productD['product_price'];
            $orderData['pay_status'] = 0;
            $orderData['order_status'] = 1;
            $orderData['create_time'] = time();
            $orderData['update_time'] = time();

            $OrderM = new OrderModel();
            $returnid_order = $OrderM->add($orderData);
            $OrderM->save();
            $data['order_id'] = $returnid_order;
            $data['create_time'] = time();

            // 查看用户是那个医生推广的。
            $spreadM = new SpreadModel ();
            $data ['doctor_id'] = $spreadM->getDoctorId($user ['openid']);
            $returnid = $bookingModel->add($data);

            //订单详情入库
            $orderDetailModel = new DetailModel();
            $orderDetailData['order_id'] = $returnid_order;
            $orderDetailData['product_id'] = OrderModel::PRODUCT_ID;
            $orderDetailData['product_num'] = 1;
            $orderDetailData['product_price'] = $productD['product_price'];
            $orderDetailData['create_time'] = time();
            $orderDetailModel->add($orderDetailData);

            // 查看用户是那个医生推广的。
//            $whereSpreadModel = array (
//                'user_penid' => $user ['openid']
//            );
//            $spreadM = new SpreadModel ();
//            $bookingModelRow = $spreadM->getRow ( $whereSpreadModel );
//            $data ['doctor_id'] = $bookingModelRow ['duser_id'];
//
//            $data ['create_time'] = time ();
////            $data ['order_no'] = date ( 'YmdHis' ) . rand ( 10000000, 99999999 );
//            $returnid = $bookingModel->add ( $data );

            // 生产订单的同事修改推广记录
            $spreadModel = new SpreadModel ();
            $status = 1;
            $spreadModel->setSpreadStatus ( $user ['openid'], $status );
        }
        else
        {
            $returnid = $bookingModelRow ['id'];
            $bookingModel->modify ( $data, $bookingModelRow ['id'] );
            $bookingD=$bookingModel->getRowById($returnid);
            $returnid_order=$bookingD['order_id'];
        }
        if ($returnid_order)
        {
            $data['id'] = $returnid_order;
            $data['booking_id'] = $returnid;
            $redata = array(
                'msg' => '获取成功',
                'result' => 1,
                'data' => $data
            );

            return json_encode($redata);
            exit();
        }
    }

    /*
     * 我的预约详情
     * */
    public function actionDetail()
    {
        $id=$this->get('id','');
        $bookingModel = new BookingModel();
        $whereUserModel =  array('id'=>$id);
        $bookingModelRow = $bookingModel->getRow($whereUserModel);

        $userModel = new zUser();
        $whereUserModel =  array('id'=>$bookingModelRow['user_id']);
        $userModelRow = $userModel->getRow($whereUserModel);
        $bookingModelRow['name'] = $userModelRow['real_name'];
        $bookingModelRow['idcard'] = $userModelRow['idcard'];
        $bookingModelRow['idcard_type'] = $userModel->getIdCardType($userModelRow['idcard_type']);
        $bookingModelRow['birthday'] = $userModelRow['birthday'];
        $bookingModelRow['mobile'] = $userModelRow['mobile'];

        //获取采血点和医生
        $bpointModel= new BpointModel();
        $bpointData=$bpointModel->getRowById($bookingModelRow['bpoint_id']);

        $staffModel = new StaffModel();
        $staffData=$staffModel->getStaffFromBid(['hospital_id' => $bookingModelRow['bpoint_id']]);
//        $doctorModel= new DoctorModel();
//        $doctorModel->columns='bc_wc_doctor.id as d_id,user_id,hospital_id,phone,bc_wc_hospital.id as h_id,name,address,bc_user.id as uid,real_name,nick_name,wxid';
//        $doctorData=$doctorModel->getDoctorList(array('bc_wc_doctor.id'=>$bookingModelRow['doctor_id']));
//        //获取这个采血点事务
//        $staffModel= new StaffModel();
//        $staffModel
        $row ['bpointData'] = $bpointData;
        $row ['staffData'] = $staffData;
        $row ['row'] = $bookingModelRow;
//        $row ['bpointData'] = $bpointData;
//        $row ['doctorData'] = $doctorData;

        return $this->render ( 'detail',$row );
    }

    /*
     * 会员中心
     * */
    public function actionMembercenter()
    {
        //更新当前用户信息
        $user = new User();
        $appid = $this->wechat()->appid;
        $secret = $this->wechat()->secret;
        $auth = new Auth($appid, $secret);
        $accessToken = $auth->accessToken;
        $info = $user->getUserInfo($accessToken, $this->openid);
        if(!empty($info))
        {
            $data = array(
                'nickname' => Util::replace_emoji($info['nickname']),
//                'wx_name' => $item['nickname'],
                'headimgurl' => $info['headimgurl']
            );

            $where =  array(
                'openid'=>$this->openid
            );

            $wxUserM = new wxUser();
            $wxUserR = $wxUserM->getRow($where);
            $wxUserM->modify($data, $wxUserR['id']);
        }
        //获取当前用户是不是医生
        $doctorM = new DoctorModel();
        $userInfoc=$doctorM->getDoctorFromOpenid($this->openid);
        if(empty($userInfoc)){
            $url='http://wx.zhishimama.com/shop/mobile/user.php';
            $this->redirect($url);
        }

        $row ['userInfoc'] = $userInfoc;
        return $this->render ( 'membercenter',$row);
    }

    /*
     * 我的推广
     * */
    public function actionPromote()
    {
        //判断是不是医生
        $doctorModel= new DoctorModel();
        $doctorModel->columns='bc_wc_doctor.id as d_id,user_id,hospital_id,phone,bc_wc_hospital.id as h_id,name,address,bc_user.id as uid,real_name,nick_name,wxid';
        $doctorData=$doctorModel->getDoctorList(array('bc_user.wxid'=>$this->openid));
        if(empty($doctorData)){
            $this->redirect('/booking/index');
        }

        //获取这个医生的信息
        if(empty($size=$_GET['size']))
            $size=0;

        $doctorList = $doctorModel->getPromotelist($size,$doctorData[0]['d_id']);

        $status1=0;
        $status2=0;
        $status3=0;
        $status4=0;
        foreach($doctorList['data'] as $k => $v)
        {
            if($v['status'] === '1' )
            {
                $status1++;
            }elseif($v['status'] === '2' ){
                $status2++;
            }elseif($v['status'] === '3' ){
                $status3++;
            }elseif($v['status'] === '4' ){
                $status4++;
            }
        }


        $row['year']=$doctorList['tmp_year'];
        $row['mon']=$doctorList['tmp_mon'];
        $row['status1']=$status1;
        $row['status2']=$status2;
        $row['status3']=$status3;
        $row['status4']=$status4;
        $row['size_s']=$size-1;
        $row['size_x']=$size+1;

        return $this->render ( 'promote',$row );
    }

    /*
     * 我的推广
     * */
    public function actionPromote1()
    {
        return $this->render ( 'promote1' );
    }

    /*
     * 我的检测
     * */
    public function actionMine()
    {
        $bookingModel = new BookingModel();
        $userInfo=$bookingModel->getUserInfo($this->openid );
        $row['userInfo'] = $userInfo;
        return $this->render ( 'mine',$row );
    }

    /*
     * 事务查询是否预约过
     * */
    public function actionSearch()
    {
        //获取当前事务的事务表id
        $confirmModel = new ConfirmModel();
        $userInfoc=$confirmModel->getUserInfoFromOpenID($this->openid);
        if(empty($userInfoc)){
            $url='/booking/index';
            $this->redirect($url);
        }
        return $this->render ( 'search');
    }

    /*
 * 事务查询是否预约过
 * */
    public function actionAjaxsearch()
    {
        $redata=array();

        $mobile = $_POST['mobile'];
        $bookingModel = new BookingModel();
        $userInfo=$bookingModel->getUserInfoFromaPhone($mobile);
//        var_dump($userInfo);
        //获取这个事务属于哪个采血点
        $staffM = new staffModel;
        $staffdata = $staffM->getStaffFromBid(['wxid' => $this->openid]);
//        var_dump($staffdata);
//        die();
        //查看事务是不是预约采血点
        if($userInfo['fid'] != 0 && $userInfo['fid'] == $staffdata[0]['hospital_id'])
        {

        }else{
            $redata['msg']='事务和预约单不属于同一个采血点';
            $redata['result']=0;
            echo json_encode($redata) ;
            die();
        }

        $userModel = new zUser();
        if(empty($userInfo)){
            $redata['msg']='搜索成功！';
            $redata['result']=0;
            echo json_encode($redata) ;
            die();
        }else{
            //判断属医生还是个人
            $price=$bookingModel->getDeduction($userInfo['border_id']);

            $user=array(
                'id'=>$userInfo['bid'],
                'name'=>$userInfo['real_name'],
                'idcard_type'=>$userModel->getIdCardType($userInfo['idcard_type']),
                'idcard'=>$userInfo['idcard'],
                'mobile'=>$userInfo['mobile'],
                'place'=>$userInfo['fname'],
                'price'=>$bookingModel::TOTAL_PRICE - $price,
            );

            //获取预约单是否有验证过
            $confirmModel = new ConfirmModel();
            $whereConfirmModel =  array('booking_id'=>$userInfo['bid']);
            $confirmRow = $confirmModel->getRow($whereConfirmModel);
            $user['confirm']=array(
                "result"=> 0,
                'data'=>array()
            );
            if(!empty($confirmRow)){
                $staffModel = new StaffModel();
                $whereStaffModel =  array('bc_wc_staff.id'=>$confirmRow['staff_id']);
                $staffRow=$staffModel->getStaffList($whereStaffModel);
                $user['confirm']=array(
                    "result"=> 1,
                    'data'=>array(
                        "confirmStaff"=> $staffRow[0]['real_name'],
                        "confirmMobile"=> $staffRow[0]['mobile'],
                        "confirmTime"=> $staffRow[0]['create_time']
                    )
                );
            }
            $redata['msg']='搜索成功！';
            $redata['result']=1;
            $redata['data']=$user;
            echo json_encode($redata) ;
        }
    }

    /*
     * 事务查询后验证
     * */
    public function actionConfirm()
    {
        //获取当前事务的事务表id
        $confirmModel = new ConfirmModel();
        $userInfoc=$confirmModel->getUserInfoFromOpenID($this->openid);
        if(empty($userInfoc)){
            $redata=array('msg'=>'你不是医院事务！','result'=>0);
            echo json_encode($redata);
            die();
        }
        $redata=array('msg'=>'验证失败！','result'=>0);
        $id = $_POST['id'];
        if(empty($id)){
            echo json_encode($redata);
            die();
        }

        $bookingModel = new BookingModel();
        $userInfo=$bookingModel->getUserInfoFromaID($id);
        $userModel = new zUser();
        if(empty($userInfo)){
            echo json_encode($redata);
            die();
        }else{
            //判断属医生还是个人
            $price=$bookingModel->getDeduction($userInfo['border_id']);

            $user=array(
                'id'=>$userInfo['bid'],
                'name'=>$userInfo['real_name'],
                'idcard_type'=>$userModel->getIdCardType($userInfo['idcard_type']),
                'idcard'=>$userInfo['idcard'],
                'mobile'=>$userInfo['mobile'],
                'place'=>$userInfo['fname'],
            	'price' => $bookingModel::TOTAL_PRICE - $price,
                'confirm'=>array(
                    "result"=>1,
                    "data" =>array(
                        "confirmStaff"=> $userInfoc['real_name'],
                        "confirmMobile"=> $userInfoc['mobile'],
                        "confirmTime"=> date('Y-m-d H:i:s', time())
                    )
                )
            );

            //如可日志表
            $confirmModel = new ConfirmModel();
            $confirmdata['booking_id']=$userInfo['bid'];
            $confirmdata['staff_id']=$userInfoc['bid'];
            $confirmdata['create_time']=time();
            if($confirmModel->add($confirmdata)){

            }
            $redata['msg']='验证成功！';
            $redata['result']=1;
            $redata['data']=$user;
            echo json_encode($redata) ;
        }


    }

    /**
     * 校验验证码
     */
    public function actionValidcode()
    {

        $msg['error'] = 1;

        if($this->getRequest()->isAjax == true)
        {
            $mobile = $this->post('mobile');
            $code = $this->post('code');
            $params['mobile'] = $mobile;

            $codeModel = new CodeModel();
            $codeModel->sort = 'id DESC';
            $code_row = $codeModel->getList(['mobile' => $mobile, 'code' => $code]);
            $msg['data'] = json_encode($code_row);
            if(!$code_row[0])
            {
                $msg['msg'] = '请输入正确的验证码';
            }
            elseif($code_row[0]['create_time'] < time() - 60 )
            {
                $msg['msg'] = '验证码已过期';
            }
            else
            {
                $msg['error'] = 0;
            }
        }

        else
        {
            $msg['msg'] = '请求异常';
        }

        echo json_encode($msg);
        exit;
    }
}